package com.example.securitydemo.service;

import com.example.securitydemo.mapper.UserMapper;
import com.example.securitydemo.po.AnotherUser;
import com.example.securitydemo.po.Role;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Package: com.example.securitydemo.service
 * @ClassName: UserService
 * @Author: Think
 * @CreateTime: 2021/7/29 13:49
 * @Description:
 */
@Slf4j
@Service
public class AnotherUserService implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    /**
     * 根据用户名去数据库获取用户信息，SpringSecutity会自动进行密码的比对
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 用户名必须是唯一的，不允许重复
        AnotherUser user = userMapper.getAnotherUserByUserName(username);
        if (ObjectUtils.isEmpty(user)) {
            throw new UsernameNotFoundException("根据用户名找不到该用户的信息！");
        }
        List<com.example.securitydemo.po.Resource> resourceList = userMapper.getUserResourceByUserId(user.getUserId());
        if (ObjectUtils.isEmpty(resourceList)) {
            log.warn("该用户没有任何权限！");
            return null;
        }
        int num = resourceList.size();
        // 定义一个数组用来存放当前用户的所有资源权限
        String[] resourceCodeArray = new String[num];
        for (int i = 0; i < num; i++) {
            resourceCodeArray[i] = resourceList.get(i).getResourceCode();
        }
        return User.withUsername(user.getUserName())
                .password(user.getPassword())
                .authorities(resourceCodeArray).build();
    }
}
